import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  message,
  Space,
  Typography,
  Divider
} from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import { createRecruitmentPlan } from "@/lib/recruitment";
import { getAllDepartments } from "@/lib/departments";
import { getAcademyList } from "@/lib/academy";
import { getAllOtherDepartments } from "@/lib/otherdept";
import { fetchEmployeeData } from "@/lib/user";

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface CreatePlanFormProps {
  onCancel: () => void;
  onSuccess: () => void;
}

interface Employee {
  value: string;
  label: string;
  department: string;
  phoneNumber: string | null;
}

const CreatePlanForm: React.FC<CreatePlanFormProps> = ({
  onCancel,
  onSuccess
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [planType, setPlanType] = useState(1);
  const [deptOptions, setDeptOptions] = useState<any[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);

  // 获取员工数据
  useEffect(() => {
    const loadEmployees = async () => {
      try {
        const response = await fetchEmployeeData({});
        if (response.data && response.data.code === 1) {
          const employeeList = response.data.data.row.map((emp: any) => ({
            value: emp.employeeId,
            label: `${emp.employeeId} - ${emp.username}`,
            department: emp.deptName,
            phoneNumber: emp.phoneNumber
          }));
          setEmployees(employeeList);
        } else {
          message.error(response.data?.msg || "获取员工数据失败");
        }
      } catch (error: any) {
        console.error("获取员工数据失败:", error);
        message.error("获取员工数据失败");
      }
    };
    loadEmployees();
  }, []);

  const fetchAvailableDepts = async (selectedPlanType: number) => {
    try {
      if (selectedPlanType === 1) {
        const response = await getAllDepartments();
        if (response.data.code === 1) {
          setDeptOptions(response.data.data);
        } else {
          message.error(response.data.msg || "获取部门数据失败");
          setDeptOptions([]);
        }
      } else if (selectedPlanType === 2) {
        const academies = await getAcademyList();
        setDeptOptions(academies);
      } else if (selectedPlanType === 3) {
        const response = await getAllOtherDepartments();
        if (response.data.code === 1) {
          setDeptOptions(response.data.data);
        } else {
          message.error(response.data.msg || "获取其他部门数据失败");
          setDeptOptions([]);
        }
      }
    } catch (error: any) {
      message.error("获取部门数据失败");
      setDeptOptions([]);
    }
  };

  useEffect(() => {
    fetchAvailableDepts(planType);
  }, [planType]);

  const handlePlanTypeChange = (value: number) => {
    setPlanType(value);
    form.resetFields(["depts"]);
    fetchAvailableDepts(value);
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const currentDate = dayjs().format("YYYY-MM-DD");
      const formattedValues = {
        ...values,
        startDate: values.startDate.format("YYYY-MM-DD"),
        endDate: values.endDate.format("YYYY-MM-DD"),
        publishDate: currentDate,
        recruitmentConditions: values.planType === 3 ? "" : values.recruitmentConditions,
        benefitsDescription: values.planType === 3 ? "" : values.benefitsDescription,
        interviewProcess: values.planType === 3 ? "" : values.interviewProcess,
        approverId: values.approver,
        approver: undefined
      };

      if (values.endDate.isBefore(values.startDate)) {
        message.error("结束日期不能早于开始日期");
        setLoading(false);
        return;
      }

      if (formattedValues.planType === 3) {
        delete formattedValues.depts;
      } else {
        if (!formattedValues.depts?.length) {
          message.error("请至少添加一个用人部门");
          setLoading(false);
          return;
        }
        for (const dept of formattedValues.depts) {
          if (!dept.positions?.length) {
            message.error(`部门 ${dept.deptSelect} 需要至少添加一个岗位`);
            setLoading(false);
            return;
          }
        }
      }

      await createRecruitmentPlan(formattedValues);
      message.success("创建成功");
      onSuccess();
    } catch (error: any) {
      message.error(error.message || "创建失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card>
      <div style={{ padding: "24px" }}>
        <Title level={2}>新增招聘计划</Title>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ approveStatus: 0, planType: 1 }}
        >
          {/* 基本信息 */}
          <Title level={4}>基本信息</Title>
          <Form.Item
            name="planName"
            label="计划名称"
            rules={[{ required: true, message: "请输入计划名称" }]}
          >
            <Input placeholder="请输入计划名称" />
          </Form.Item>
          <Form.Item
            name="planCode"
            label="计划编号"
            rules={[{ required: true, message: "请输入计划编号" }]}
          >
            <Input placeholder="请输入计划编号" />
          </Form.Item>
          <Form.Item
            name="planType"
            label="计划类型"
            rules={[{ required: true, message: "请选择计划类型" }]}
          >
            <Select onChange={handlePlanTypeChange}>
              <Option value={1}>管理岗位</Option>
              <Option value={2}>专任教师</Option>
              <Option value={3}>其他岗位</Option>
            </Select>
          </Form.Item>

          {/* 时间信息 */}
          <Title level={4}>时间信息</Title>
          <Form.Item
            name="startDate"
            label="开始日期"
            rules={[{ required: true, message: "请选择开始日期" }]}
          >
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item
            name="endDate"
            label="结束日期"
            rules={[
              { required: true, message: "请选择结束日期" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || !getFieldValue('startDate') || value.isAfter(getFieldValue('startDate'))) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('结束日期必须晚于开始日期'));
                },
              }),
            ]}
          >
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>

          {/* 部门和岗位信息 */}
          {planType !== 3 && (
            <>
              <Title level={4}>部门和岗位信息</Title>
              <Form.List name="depts">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Card key={key} style={{ marginBottom: 16 }}>
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Form.Item
                            {...restField}
                            name={[name, 'deptSelect']}
                            label="用人部门"
                            rules={[{ required: true, message: '请选择用人部门' }]}
                          >
                            <Select placeholder="请选择用人部门">
                              {deptOptions.map((dept: any) => (
                                <Option key={dept.id} value={dept.id}>
                                  {dept.deptName}
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>

                          <Form.List name={[name, 'positions']}>
                            {(posFields, { add: addPos, remove: removePos }) => (
                              <>
                                {posFields.map(({ key: posKey, name: posName, ...restPosField }) => (
                                  <Space key={posKey} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                    <Form.Item
                                      {...restPosField}
                                      name={[posName, 'positionName']}
                                      rules={[{ required: true, message: '请输入岗位名称' }]}
                                    >
                                      <Input placeholder="岗位名称" />
                                    </Form.Item>
                                    <Form.Item
                                      {...restPosField}
                                      name={[posName, 'count']}
                                      rules={[{ required: true, message: '请输入招聘人数' }]}
                                    >
                                      <Input type="number" placeholder="招聘人数" />
                                    </Form.Item>
                                    <MinusCircleOutlined onClick={() => removePos(posName)} />
                                  </Space>
                                ))}
                                <Form.Item>
                                  <Button type="dashed" onClick={() => addPos()} block icon={<PlusOutlined />}>
                                    添加岗位
                                  </Button>
                                </Form.Item>
                              </>
                            )}
                          </Form.List>
                        </Space>
                        <Button type="link" danger onClick={() => remove(name)}>
                          删除此部门
                        </Button>
                      </Card>
                    ))}
                    <Form.Item>
                      <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        添加用人部门
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </>
          )}

          {/* 其他信息 */}
          {planType !== 3 && (
            <>
              <Title level={4}>其他信息</Title>
              <Form.Item
                name="recruitmentConditions"
                label="招聘条件"
                rules={[{ required: true, message: "请输入招聘条件" }]}
              >
                <TextArea rows={4} placeholder="请输入招聘条件" />
              </Form.Item>

              <Form.Item
                name="benefitsDescription"
                label="待遇说明"
                rules={[{ required: true, message: "请输入待遇说明" }]}
              >
                <TextArea rows={4} placeholder="请输入待遇说明" />
              </Form.Item>

              <Form.Item
                name="interviewProcess"
                label="面试流程"
                rules={[{ required: true, message: "请输入面试流程" }]}
              >
                <TextArea rows={4} placeholder="请输入面试流程" />
              </Form.Item>
            </>
          )}

          {/* 审批人 */}
          <Title level={4}>审批信息</Title>
          <Form.Item
            name="approver"
            label="审批人"
            rules={[{ required: true, message: "请选择审批人" }]}
          >
            <Select
              showSearch
              placeholder="请选择审批人"
              optionFilterProp="children"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={employees}
            />
          </Form.Item>

          {/* 提交按钮 */}
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
              <Button onClick={onCancel}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </Card>
  );
};

export default CreatePlanForm; 